package cn.guetzjb.security.interceptor;

import cn.guetzjb.core.constant.SecurityConstants;
import cn.guetzjb.core.context.SecurityContextHolder;
import cn.guetzjb.security.utils.AuthUtil;
import cn.guetzjb.sys.model.LoginUser;
import com.alibaba.nacos.common.utils.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

@Component
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String userId = request.getHeader(SecurityConstants.DETAILS_USER_ID);
        String username = request.getHeader(SecurityConstants.DETAILS_USERNAME);
        String userKey = request.getHeader(SecurityConstants.USER_KEY);
        String token = request.getHeader(SecurityConstants.AUTHORIZATION_HEADER);
        SecurityContextHolder.setUserId(userId);
        SecurityContextHolder.setUserName(username);
        SecurityContextHolder.setUserKey(userKey);

        if (!StringUtils.isEmpty(token)) {
            LoginUser loginUser = AuthUtil.getLoginUser(token);
            SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SecurityContextHolder.remove();
    }
}
